/*
=================================================================
= Title: NatLib  
= Desc: Collection of javascript functions to display google charts with Nabton data 
= Author: Adam Saxén
= Copywrite Nabton.com 2014
= Revision history: 
= 2014-07-14 - Added comments to library  
=================================================================
*/

//#### Initial variables
var currentData; //Current Graph data
var googleChart; //Handle to chart

var changeT = 0; // If equal to 2 update graph

var maxVal;
var minVal;

//Select data from graph variables
var start;
var stop;

var dataF;

function updateCurrentPower() {
    console.log("currentPowerCalled");
    $.get("nabPublic/power_upd.php?id=1234", {
        user: '1'
    }, function (data) {
        $("#infoBox").html(data);
    });
    setTimeout('updateCurrentPower()', 2000);
}

var options = {
    // width: 700,
    height: 440,
    title: 'Power Consumption',
    baseTitle: 'Power Consumption',
    series: {
        0: {
            color: '#ff7e00'
        },
        1: {
            color: '#CCCCCC'
        },
    },
    chartArea: {
        'width': '75%',
        'height': '70%'
    },
    legend: {
        'position': 'none'
    },
    hAxis: {
        format: 'kk:mm:ss',
        viewWindowMode: 'explicit',
        viewWindow: {
            min: 0,
            max: 0
        }
    },
    vAxis: {
        title: "Watt",
        viewWindowMode: 'explicit',
        viewWindow: {
            max: 0,
            min: 0
        }
    }

};


//#############################################
//# Function call
//# Description: Called when page is loaded and ready
//#############################################
jQuery(document).ready(function ($) {
    console.log("ready!");

    updateCurrentPower();
    loadChart();

    $.ajax({
        url: 'nabPublic/dispatch.php', // Call goes to where?
        dataType: 'json', // What data to expect
        success: selDataHandler,
        error: errorHandler,
        type: 'GET', // GET eller POST beroende på vad du vill använda

        data: { // Data vi skall skicka som POST eller GET, Detta blir ex. $_GET['username'] eller $_POST['username'] i 'dispatch.php'
            action: 'sel_data',
            ff: 'a'
        }
    });


    $('#form1').change(function (e) {
        e.preventDefault();

        console.log("Update chart!");
        loadChart();

    });

    $('#resetZoom').click(function (e) {
        e.preventDefault();

        console.log("Update chart!");
        updateChart(1);

    });




    //Populate selection input in form 
    function selDataHandler(data) {
        // SUCCESS, data innehåller responsen från sidan
        console.log('selDataHandler - called');
       // console.log(data); // Skriv ut i konsolen för att se innehållet
        
        $.each(data.reverse(), function (key, value) {
            var dateArr = value.split("-");
            var dateLast = dateArr[4].split(".");
            console.log("values: "+ value);
            $('#selData')
                .append($("<option></option>")
                    .attr("value", value)
                    .text(dateArr[2]+"-"+dateArr[3]+"-"+dateLast[0]));
        });

    }


});

//#############################################
//# Function - loadChart() 
//# Description: Called once to initiate and load chart
//#############################################
function loadChart() {
    var path = $('#selData').val();

    if (path == null && path == undefined) {
        path = "a";
    }

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "nabPublic/dispatch.php",
        data: {
            ff: path,
            action: 'update_chart'
        },
        success: function (data) {
            // Create and draw the visualization.

            var v = new google.visualization.ColumnChart(
                document.getElementById('chart_div')
            );

            googleChart = v;

            // Listen for the 'select' event, and call my function selectHandler() when
            // the user selects value on the chart.
            google.visualization.events.addListener(v, 'select', selectHandler);

            //Set temporary max an min value for y-axis			   
            maxVal = data[0][1];
            minVal = data[0][1];

            for (i = 0; i < data.length; i++) {

                //Filter high power values
                if (data[i][1] > 20000) {

                    console.log("Maximum log value exceeded: " + data[i][1]);
                    data[i][1] = 0;
                }

                if (data[i][1] > maxVal) {
                    maxVal = data[i][1];
                }

                if (data[i][1] < minVal) {
                    minVal = data[i][1];
                }



                //Format time to date format
                var tt = data[i][0].split(":");
                data[i][0] = new Date();
                data[i][0].setHours(tt[0]);
                data[i][0].setMinutes(tt[1]);
                data[i][0].setSeconds(tt[2]);
            }

            var dataM = data.length;


           

            dataF = google.visualization.arrayToDataTable(data, true);
            var formatter = new google.visualization.DateFormat({
                pattern: "kk:mm:ss"
            });
            // Reformat data.
            formatter.format(dataF, 0);

            //Called when user clicks on chart
            function selectHandler() {
                var selectedItem = v.getSelection()[0];
                if (selectedItem) {


                    // Determin if user clicks first or second time
                    switch (changeT) {
                    case 0:
                        start = dataF.getValue(selectedItem.row, 0);
                        changeT = 1;
                        break;
                    case 1:
                        stop = dataF.getValue(selectedItem.row, 0);
                        changeT = 0;
                        updateChart(0);
                        break;
                    }

                }
            }


            //Set max min values
            options.hAxis.viewWindow.min = data[1][0];
            options.hAxis.viewWindow.max = data[dataM - 1][0];

            options.vAxis.viewWindow.min = 0;
            options.vAxis.viewWindow.max = maxVal;

            options.title = options.baseTitle + " (" + (dataM/1000) + " kWh)"; 


            currentData = dataF;


            v.draw(dataF, options);


        },
        error: errorHandler
    });

}

//#############################################
//# Function - updateChart(int d) 
//# Description: Determine how to update chart based on input paramter d
//#############################################
function updateChart(d) {

    switch (d) {
    case 0: //Zoom

        var s_i = 0; //Start index
        var e_i = 10; // Stop index

        var max_t = 0.0;
        var min_t = 0.0;

        //Find correct indeces		 
        for (i = 0; i < currentData.getNumberOfRows(); i++) {
            var cc = currentData.getValue(i, 0);


            if (cc.getTime() == start.getTime()) {
                s_i = i;
            }

            if (cc.getTime() == stop.getTime()) {
                e_i = i;
            }
        }

        //Validate interval - Shift if needed
        if (s_i > e_i) {
            s_i ^= e_i;
            e_i ^= s_i;
            s_i ^= e_i;
        }

        console.log("s_id e_i " + s_i + ":" + e_i);
        var good = 0;
        for (j = s_i; j < e_i; j++) {
            var good = currentData.getValue(j, 1);

            if (good >= max_t) {
                console.log("found new max!");
                max_t = good;
            }

            if (good <= min_t) {
                min_t = 0;
            }

        }

        //Set max min values
        options.hAxis.viewWindow.min = currentData.getValue(s_i, 0);
        options.hAxis.viewWindow.max = currentData.getValue(e_i, 0);

        options.vAxis.viewWindow.min = 0;
        options.vAxis.viewWindow.max = max_t;
        options.title = options.baseTitle + " (" + (((e_i-s_i)+1)/1000) + " kWh)"; 

        googleChart.draw(currentData, options); //Update graph	
        break;
    case 1: //Reset

        //Set max min values
        options.hAxis.viewWindow.min = currentData.getValue(0, 0);
        options.hAxis.viewWindow.max = currentData.getValue(currentData.getNumberOfRows() - 1, 0);

        options.vAxis.viewWindow.min = 0;
        options.vAxis.viewWindow.max = maxVal;
        options.title = options.baseTitle + " (" + (currentData.getNumberOfRows()/1000) + " kWh)"; 

        googleChart.draw(currentData, options); //Update graph	

        break;
    case 2:

        break;

    }
}

//#############################################
//# Function - errorHandler() 
//# Description: Called when ajax-post fails. Prints error to console
//#############################################
function errorHandler(x, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
}